package dumu

import (
	"encoding/json"
	"errors"
	"fsdvgw/repo"
	"github.com/go-resty/resty/v2"
	"time"
)

const ModelName = "DMCM01110-B"

type dumu struct {
	ip       string
	password string
}

func newDumu(dev *repo.Dev) *dumu {
	return &dumu{
		ip:       "http://" + dev.IP + ":8080",
		password: dev.Context,
	}
}

func (dumu *dumu) registerUser(param *registerUserParam) (any, error) {
	if param.UserId == "" || param.PersonName == "" || param.ImgBase64 == "" {
		return nil, errors.New("注册人脸信息的参数缺失")
	}
	apiParam := uploadPersonFaceRequest{
		Pass:         dumu.password,
		UserId:       param.UserId,
		ImageContent: param.ImgBase64,
		ImageType:    "image",
		UserInfo:     userInfo{Name: param.PersonName, UserType: 1},
	}
	apiParamBytes, err := json.Marshal(apiParam)
	if err != nil {
		return nil, err
	}

	response, err := request().SetBody(apiParamBytes).Post(dumu.ip + "/userManage/addUser")
	if err != nil {
		return nil, err
	}

	responseInfo := &uploadPersonInfoResponse{}
	err = json.Unmarshal(response.Body(), responseInfo)
	if err != nil {
		return nil, err
	}
	if responseInfo.Code < 0 {
		return nil, errors.New(responseInfo.Log)
	}
	return nil, nil
}

func (dumu *dumu) removeUser(param *removeUserParam) (any, error) {
	if param.UserId == "" {
		return nil, errors.New("删除人脸信息的参数缺失")
	}
	apiParam := &removePersonFaceRequest{
		Pass:   dumu.password,
		UserId: param.UserId,
	}
	apiParamBytes, err := json.Marshal(apiParam)
	if err != nil {
		return nil, err
	}

	response, err := request().SetBody(apiParamBytes).Post(dumu.ip + "/userManage/deleteUser")
	if err != nil {
		return nil, err
	}

	responseInfo := &baseResponse{}
	err = json.Unmarshal(response.Body(), responseInfo)
	if err != nil {
		return nil, err
	}
	if responseInfo.Code < 0 {
		if responseInfo.Log != "'deleteUser' no such uuid" {
			return nil, errors.New(responseInfo.Log)
		}

	}
	return nil, nil
}

func request() *resty.Request {
	return resty.New().SetTimeout(5*time.Second).R().
		SetHeader("Accept", "*/*").
		SetHeader("Content-Type", "application/json")
}
